package com.base.cn.platform.os.entity.user.account;

import com.base.cn.platform.os.common.mybatis.BaseEntity;
import com.base.cn.platform.os.common.utils.user.AccountStatus;
import com.base.cn.platform.os.common.utils.user.AccountType;
import com.base.cn.platform.os.entity.user.user.CusUser;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;


/**
 * 账户
 *
 * @author ll
 * @create 2018-04-24
 */
@Data
public class CusUserAccount extends BaseEntity{

    private BigDecimal userId;// 用户id
    private BigDecimal balance;// 账户余额
    private BigDecimal cashAmount;// 银行入账
    private BigDecimal cashForzenAmount;// 银行充值冻结金额
    private BigDecimal vmAmount;// 充值卡入账
    private BigDecimal vmForzenAmount;// 充值卡金额冻结金额
    private String accountStatus;// 账户状态    ACTIVE, // 正常    FROZEN// 冻结
    private BigDecimal applyCashAmount;// 申请的提现总金额
    private Long version;// 乐观锁版本号
    //用户对象
    private CusUser user;

    /**
     * 入款
     *
     * @param amount 入款金额
     * @param accountType 入款类型
     * @param amount
     */
    public void credit(BigDecimal amount, String accountType) {
        amount = CusUserAccount.formatBigDecimal(amount);
        if (amount.doubleValue() < 0) {
            throw new IllegalArgumentException("amount must be > 0");
        }
        setBalance(CusUserAccount.formatBigDecimal(this.balance.add(amount)));
        // cash 和vm
        if (AccountType.CASH.toString().equals(accountType)) {
            setCashAmount(CusUserAccount.formatBigDecimal(this.cashAmount.add(amount)));
        } else if (AccountType.VM.toString().equals(accountType)) {
            setVmAmount(CusUserAccount.formatBigDecimal(this.vmAmount.add(amount)));
        }

    }

    /**
     * 出款
     *
     * @param amount
     */
    public void debit(BigDecimal amount) {
        if (amount.doubleValue() < 0) {
            throw new IllegalArgumentException("amount must be > 0");
        }
        // 扣款时账户如果被冻结了。不准消费
        if (!AccountStatus.ACTIVE.toString().equals(getAccountStatus().toString())) {
            throw new IllegalStateException("account status is invalid");
        }
        setBalance(CusUserAccount.formatBigDecimal(this.balance.subtract(amount)));

        // 设置cashAmount和vmAmount,出款时先扣除vm,不够时再扣除cash
        if (this.getVmAmount().compareTo(amount) >= 0) {// vm余额大于等于扣款的金额
            this.setVmAmount(CusUserAccount.formatBigDecimal(this.getVmAmount().subtract(amount)));
        } else {// vm不够的时候 再扣除cash的余额
            BigDecimal didAmount = amount.subtract(this.getVmAmount());// 需要扣除的cash的金额
            this.setVmAmount(new BigDecimal(0));// vm设置为0
            this.setCashAmount(CusUserAccount.formatBigDecimal(this.cashAmount.subtract(didAmount)));
        }
    }

    public static BigDecimal formatBigDecimal(BigDecimal decimal) {
        return decimal.setScale(2, RoundingMode.HALF_UP);
    }
}
